<?php

namespace common\models;

use app\models\AdminLog;
use common\utils\XCache;
use Yii;

/**
 * This is the model class for table "banner".
 *
 * @property string $id
 * @property string $name
 *
 * @property BannerItem[] $bannerItems
 */
class Banner extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'banner';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name'], 'string', 'max' => 64],
            [['name'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBannerItems()
    {
        return $this->hasMany(BannerItem::className(), ['banner_id' => 'id']);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            AdminLog::log("新添幻灯片：" . $this->name, "create");
        } else {
            AdminLog::log("更新幻灯片：旧：" . $changedAttributes['name'] . "；新：" . $this->name);
        }
    }

    public function afterDelete()
    {
        parent::afterDelete();
        AdminLog::log("删除幻灯片：" . $this->name, "delete");
        XCache::bannerDelete($this->name);
    }

    /**
     * @param string $name 幻灯片名称
     * @return array Banner图片
     */
    public static function photos($name)
    {
        /*$model = Banner::findOne(['name' => $name]);
        if ($model) {
            return BannerItem::find()->select("src,title,url")->where("banner_id=$model->id")->orderBy("sort asc")->asArray()->all();
        }
        return [];*/
        return XCache::banner($name);
    }
}
